<template>
<div class="add_task">
    <el-title :title="title"></el-title>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="事项类别:" prop="name" v-if="power">
            <el-select v-model="ruleForm.name" filterable placeholder="请选择" @change="nowList()">
                <el-option
                v-for="item in danList"
                :key="item.value"
                :label="item.class_name"
                :value="item.class_id">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="事项名称:" prop="genre" v-if="power">
            <el-select v-model="ruleForm.genre" placeholder="请选择">
                <el-option
                v-for="item in optionsd"
                :key="item.value"
                :label="item.name"
                :value="item.id">
                </el-option>
            </el-select>
        </el-form-item>
        <!-- <el-form-item label="计划日期:" prop="date" v-if="power">
            <el-date-picker
                v-model="ruleForm.date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
            </el-date-picker>
        </el-form-item> -->
        <el-form-item label="呼叫单位:" prop="einheit" v-if="power">
            <el-select v-model="ruleForm.einheit" multiple filterable placeholder="请选择">
                <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.realname"
                :value="item.userid">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="联系号码:" prop="phone">
            <el-input v-model.number="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="具体情形:" prop="statement" class="explain">
            <el-input type="textarea" v-model="ruleForm.explain" ></el-input>
        </el-form-item>
        <el-form-item label="上传图片:" class="uppic">
            <el-upload
            ref="pictureUpload" 
            action="/api/project/upload"
            list-type="picture-card"
            :on-success="handlePreview"
            :on-error="handleError"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :file-list="fileList"
            multiple
            >
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url" alt=""
                >
                <span class="el-upload-list__item-actions">
                    <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                    >
                    <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                    >
                    <i class="el-icon-delete"></i>
                    </span>
                </span>
                </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
        </el-form-item>

        <el-form-item label="上传视频:" class="uppic">
            <el-upload
                class="upload-demo"
                drag
                action="/api/project/upload?type=102"
                :on-success="handleVideoSuccess"
                :show-file-list="false"
                :disabled="videoDis"
                multiple>
                <span
                v-if="videoForm.showVideoPath !='' && !videoFlag"
                class="eldelete"
                @click="videoRemove"
                >
                <i class="el-icon-delete"></i>
                </span>
                    <video v-if="videoForm.showVideoPath !='' && !videoFlag"
                            :src="videoForm.showVideoPath"
                            class="avatar video-avatar"
                            controls="controls">
                    </video>
                    <i v-else-if="videoForm.showVideoPath =='' && !videoFlag" class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
    </el-form-item>
				<el-form-item label="上传附件:" class="uppic">
			<el-upload
			  class="upload-demo upload_appen"
			  action="/api/project/upload?type=103"
			  :on-success="handleAppenPreview"
			  :on-remove="handleAppenRemove"
			  multiple
			  >
	  <el-button size="small" type="primary">点击上传</el-button>
	</el-upload>
		</el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交编辑</el-button>
        </el-form-item>
    </el-form>
</div>
</template>

<script>
import elTitle from '@/components/title'
import {uploadRemove,addTask,userUnit,taskDetails,projectmain,apiassociat,userInfo,varEdit} from '@/utils/index.js'
export default {
    data(){
        var username = (rule, value, callback) => {
            if (value === '') {
                this.$message.closeAll()
                this.$message.warning('项目名称不能为空')
                callback(new Error(' '));
            } else {
                callback();
            }
        };
        var type = (rule, value, callback) => {
            if (value === '') {
                this.$message.closeAll()
                this.$message.warning('任务类型不能为空')
                callback(new Error(' '));
            } else {
                callback();
            }
        };
        var date = (rule, value, callback) => {
            if (value === '') {
                this.$message.closeAll()
                this.$message.warning('计划日期不能为空')
                callback(new Error(' '));
            } else {
                callback();
            }
        };
        var company = (rule, value, callback) => {
            if (value === '') {
                this.$message.closeAll()
                this.$message.warning('选择单位不能为空')
                callback(new Error(' '));
            } else {
                callback();
            }
        };
        var explain = (rule, value, callback) => {
            if (value === '') {
                this.$message.closeAll()
                this.$message.warning('任务说明不能为空')
                callback(new Error(' '));
            } else {
                callback();
            }
        };
        var phone = (rule, value, callback) => {
            if (value === '') {
                this.$message.closeAll()
                this.$message.warning('联系电话不能为空')
                callback(new Error(' '));
            } else {
                callback();
            }
        };
        return{
            // 上传视频
            videoFlag: false,
            //是否显示进度条
            videoUploadPercent: "",
            //进度条的进度，
            isShowUploadVideo: false,
            //显示上传按钮
            videoForm: {
                showVideoPath: '',
                id:''
            },
            // 结束上传
            videoDis:false,
            title:'创建任务',
            ruleForm: {
                name:'',
                genre: '',
                phone:'',
                date: '',
                einheit: '',
                explain:''
            },
            rules: {
                name: [
                    { validator: username, trigger: 'blur' }
                ],
                genre: [
                    { validator: type, trigger: 'blur' }
                ],
                date: [
                    { validator: date, trigger: 'blur' }
                ],
                einheit: [
                    { validator: company, trigger: 'blur' }
                ],
                explain: [
                    { validator: explain, trigger: 'blur' }
                ],
                phone: [
                    { validator: phone, trigger: 'blur' }
                ],
            },
            optionsd:[],
            options:[],
            danList:[],
            // 上传图片
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            file:[],
            fileList:[],
            videoDate:'',
            power:true,
        }
    },
    components:{
        elTitle
    },
    beforeCreate(){
        userInfo().then((res)=>{
            if(res.data.member == 0){
                this.power = false
            }
        })
        // 详情
        taskDetails({
            id:this.$route.query.supid
        }).then((res)=>{
            console.log(res)
            let data = res.data
            let arr = Object.keys(this.ruleForm)
            // 给data字段赋值
            for (let key in data) {
                if (arr.indexOf(key) > -1) {
                    this.ruleForm[key] = data[key]
                }
            }
            this.ruleForm.date =[new Date(parseInt(res.data.stime)*1000),new Date(parseInt(res.data.etime)*1000)]
            if(res.data.video == ""){
                this.videoDis = false
            }else{
                this.videoForm.showVideoPath = res.data.video[0].src
                this.videoForm.id = res.data.video[0].id
                this.file.push(res.data.video[0])
                this.videoDis = true
            }
            let lists = res.data.pic
            lists.forEach((item) => {
                this.fileList.push({url:item.src,id:item.id})
                this.file.push(item)
            });
            // 事项名称
            console.log(this.ruleForm.name)
            apiassociat({
                class_id:this.ruleForm.name
            }).then((res)=>{
                console.log(res)
                this.optionsd = res.data
            })

            this.ruleForm.name=null
            this.ruleForm.genre=null
            this.ruleForm.einheit=null

        })
    },
    created(){
        // 获取单位
        userUnit().then((res)=>{
            console.log(res)
            this.options = res.data
        })
        // 事项类别
        projectmain().then((res)=>{
            console.log(res)
            this.danList = res.data
        })
        
    },
    methods:{
        nowList(){
            console.log(this.ruleForm.name)
            apiassociat({
                class_id:this.ruleForm.name
            }).then((res)=>{
                console.log(res)
                this.optionsd = res.data
                this.ruleForm.genre = ''
            })
        },
        //上传成功回调
        handleVideoSuccess(res) {
            this.isShowUploadVideo = true;
            this.videoFlag = false;
            this.videoUploadPercent = 0;
            console.log(res)
            //后台上传地址
            if (res.code == 0) {
                this.videoForm.id = res.data.id
                this.videoForm.showVideoPath = res.data.src;
                this.file.push(res.data)
                this.videoDis = true
            }
        },
        // 上传图片
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        // 上传成功
        handlePreview(file){
            console.log(file)
            this.file.push(file.data)
            console.log(this.file)
            this.$message.closeAll()
            this.$message.success('上传成功')
        },
        // 失败
        handleError(file){
            console.log(file)
        },
        // 移除视频
        videoRemove(){
            console.log(this.videoForm.id)
            uploadRemove({
                id:this.videoForm.id
            }).then((res)=>{
                if(res.code == '0'){
                    // 1.从pics数组中，找到图片对应的索引值
                    let j = this.file.findIndex((x)=>x.id == this.videoForm.id)
                    // 2.调用splice方法，移除图片信息
                    this.file.splice(j, 1)
                    console.log(this.file)

                    this.videoForm.showVideoPath = ""
                    this.videoForm.id = ""
                    this.videoDis = false
                    console.log(this.videoForm)
                    this.$message.closeAll()
                    this.$message.success(res.msg)
                }else{
                    this.$message.closeAll()
                    this.$message.warning(res.msg)
                }
            })
        },
        // 移除图片
        handleRemove(file){
            console.log(file)
            uploadRemove({
                id:file.id
            }).then((res)=>{
                console.log(res)
                if(res.code == '0'){
                    // 移除file中数据
                    // 1.从pics数组中，找到图片对应的索引值
                    let j = this.file.findIndex((x)=>x.id == file.id)
                    // 2.调用splice方法，移除图片信息
                    this.file.splice(j, 1)
                    console.log(this.file)
                    // 删除预览图片
                    let uploadFiles = this.$refs.pictureUpload.uploadFiles
                    for (var i = 0; i < uploadFiles.length; i++) {
                        if (uploadFiles[i]['url'] == file.url) {
                            uploadFiles.splice(i, 1)
                        }
                    }
                    this.$message.closeAll()
                    this.$message.success(res.msg)
                }else{
                    this.$message.closeAll()
                    this.$message.warning(res.msg)
                }
            })
        },
        beforeUpload(file){
            console.log(file)
        },
        //上传图片end
				// 上传附件
		handleAppenPreview(file){
			console.log(file)
			this.file.push(file.data)
			console.log(this.file)
			this.$message.closeAll()
			this.$message.success('上传成功')
		},
		handleAppenRemove(file){
			console.log(file)
		    uploadRemove({
		        id:file.response.data.id
		    }).then((res)=>{
		        if(res.code == '0'){
		            // 移除file中数据
		            // 1.从pics数组中，找到图片对应的索引值
		            let j = this.file.findIndex((x)=>x.id == file.response.data.id)
		            // 2.调用splice方法，移除图片信息
		            this.file.splice(j, 1)
		            console.log(this.file)
		            this.$message.closeAll()
		            this.$message.success(res.msg)
		        }else{
		            this.$message.closeAll()
		            this.$message.warning(res.msg)
		        }
		    })
		},
        // 提交
        submitForm(formName) {
            console.log(this.file)
            this.$refs[formName].validate((valid) => {
            if (valid) {
                if(this.power == false){
                    varEdit({
                        id:this.$route.query.supid,
                        phone:this.ruleForm.phone,
                        explain:this.ruleForm.explain,
                        file:this.file
                    }).then((res)=>{
                        if(res.code == '0'){
                            this.$message.closeAll()
                            this.$message.success('修改成功')
                            
                            setTimeout(()=>{
                                this.$router.push('/my_task')
                            },800)
                        }else{
                            this.$message.closeAll()
                            this.$message.warning(res.msg)
                        }
                    })
                }else{
                    addTask({
                        supid:this.$route.query.supid,
                        name:this.ruleForm.name,
                        genre:this.ruleForm.genre,
                        stime:this.ruleForm.date[0],
                        etime:this.ruleForm.date[1],
                        cate_id:this.ruleForm.einheit,
                        phone:this.ruleForm.phone,
                        explain:this.ruleForm.explain,
                        file:this.file
                    }).then((res)=>{
                        console.log(res)
                        if(res.code == '0'){
                            this.$message.closeAll()
                            this.$message.success('添加成功')
                            setTimeout(()=>{
                                this.$router.push('/my_task')
                            },800)
                        }else{
                            this.$message.closeAll()
                            this.$message.warning(res.msg)
                        }
                    })
                }
            } else {
                console.log('error submit!!');
                return false;
            }
            });
        },
    }
}
</script>

<style lang="scss" scoped>
.demo-ruleForm::v-deep{
    margin-top: 15px;
    padding:50px 30px !important;
    background-color: white;
    padding: 40px 0;
    .el-form-item{
        display: inline-block;
        width: 500px;
        margin-bottom: 30px;
    }
    .el-form-item__label{
        width: 130px !important;
    }
    .el-form-item__content{
        margin-left: 130px !important;
    }
    .uppic{
        display: block;
        width: 100%;
        .el-upload-list__item{
            div{
                height: 146px;
            }
        }
    }
    .el-select{
        width: 100%;
    }
    .explain{
        display: block;
        width: 92%;
        .el-textarea__inner{
            height: 120px;
        }
    }
}
video{
    height: 100%;
    width: 300px;
}
.eldelete{
    position: absolute;
    right: 7px;
    font-size: 18px;
    color: #333;
}
.eldelete:hover {
    color: red;
}
.upload_appen {
	.el-upload-list__item {
		width: 50%;
	}
}
</style>





